from rest_framework.views import APIView
from rest_framework.response import Response

from luckin.authentication import TokenAuthentication
from luckin.service.shipping_address import ShippingAddressService
from luckin.serialization import ShippingAddressSerializers


# 收获地址增删改查
class ShippingAddress(APIView):
    authentication_classes = [TokenAuthentication]

    def get(self, request, *args, **kwargs):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shipping_address = ShippingAddressService()
        flag, data = shipping_address.get(request)
        if flag:
            if data:
                ser = ShippingAddressSerializers(data, many=True)
                address_data = ser.data
            else:
                address_data = data
            response_data["data"] = address_data
        else:
            response_data["code"] = 400
            response_data["message"] = data

        return Response(status=200, content_type="application/json", data=response_data)

    def post(self, request, *args, **kwargs):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shipping_address = ShippingAddressService()
        flag, data = shipping_address.post(request)
        if flag:
            ser = ShippingAddressSerializers(data, many=False)
            address_data = ser.data
            response_data["data"] = address_data
        else:
            response_data["message"] = data

        return Response(status=200, content_type="application/json", data=response_data)

    def put(self, request, *args, **kwargs):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shipping_address = ShippingAddressService()
        flag, data = shipping_address.put(request)
        if not flag:
            response_data["message"] = data

        return Response(status=200, content_type="application/json", data=response_data)

    def delete(self, request, *args, **kwargs):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shipping_address = ShippingAddressService()
        flag, data = shipping_address.delete(request)
        if not flag:
            response_data["message"] = data

        return Response(status=200, content_type="application/json", data=response_data)
